package com.lepu.app.fun.chat.activity;

import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.AsyncRequest;
import com.core.lib.core.HttpRequest.OnRequestComplete;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.photo.UniversalImageLoadTool;
import com.core.lib.widget.CircularImageView;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.chat.bean.BeanChatTo;
import com.lepu.app.fun.chat.bean.BeanDoctorMyDetail;
import com.lepu.app.fun.chat.bean.ChatSession;
import com.lepu.app.fun.chat.business.DoctorManager;
import com.lepu.app.fun.chat.core.ChatManager;
import com.lepu.app.fun.chat.util.ChatConst;
import com.lepu.app.fun.chat.util.ChatUtil;
import com.lepu.app.fun.chat.util.Constants;
import com.lepu.app.fun.index.activity.IndexConsultActivity;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

public class DoctorMyDetailActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest {

	public static final String REQUEST_DATA = "request_data";

	private static final int MSG_RELEASE_DOCTOR_SUCCESS = 10;
	private static final int MSG_RELEASE_DOCTOR_FAIL = 11;

	private BeanDoctorMyDetail mBeanDoctorMyDetail = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat_doctor_my_detail_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("医生资料");
		topbar.setonTopbarNewLeftLayoutListener(this);

		String DoctorID = getIntent().getStringExtra("DoctorID");

		RelativeLayout contentLayout = (RelativeLayout) findViewById(R.id.contentLayout);
		contentLayout.setVisibility(View.GONE);

		showProgressDialog();
		DoctorManager.getInstance().requestDoctorDetail(this, DoctorID);
	}

	private void initData() {

		RelativeLayout contentLayout = (RelativeLayout) findViewById(R.id.contentLayout);
		contentLayout.setVisibility(View.VISIBLE);

		CircularImageView accountIconImageView = (CircularImageView) findViewById(R.id.accountIconImageView);
		accountIconImageView
				.setImageResource(R.drawable.chat_doctor_icon_default);

		UniversalImageLoadTool.disPlay(
				Setting.getImageUrl(mBeanDoctorMyDetail.Avatar),
				accountIconImageView, R.drawable.chat_doctor_icon_default);

		TextView hospitalNameTextView = (TextView) findViewById(R.id.hospitalNameTextView);
		TextView keNameTextView = (TextView) findViewById(R.id.keNameTextView);
		TextView nameTextView = (TextView) findViewById(R.id.nameTextView);
		TextView zhuZhiTextView = (TextView) findViewById(R.id.zhuZhiTextView);
		TextView jobTextView = (TextView) findViewById(R.id.jobTextView);
		TextView countTextView = (TextView) findViewById(R.id.countTextView);
		TextView areaTextView = (TextView) findViewById(R.id.areaTextView);
		TextView goodAtTextView = (TextView) findViewById(R.id.goodAtTextView);
		TextView workTimeTextView = (TextView) findViewById(R.id.workTimeTextView);

		hospitalNameTextView.setText(mBeanDoctorMyDetail.HospitalName);
		keNameTextView.setText(mBeanDoctorMyDetail.DepartmentName);
		nameTextView.setText(mBeanDoctorMyDetail.DoctorName);
		zhuZhiTextView.setText(mBeanDoctorMyDetail.JobTitle);
		jobTextView.setText(mBeanDoctorMyDetail.TeachJobTitle);
		countTextView.setText(mBeanDoctorMyDetail.TotalPatient + "位患者");

		areaTextView.setText("地区：" + mBeanDoctorMyDetail.AreaName);
		goodAtTextView.setText("擅长治疗：" + mBeanDoctorMyDetail.Skill);
		workTimeTextView.setText("门诊时间：" + mBeanDoctorMyDetail.OutpatientTime);

	}

	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.sendMessageTextView:

			Activity chatMainActivity = AppManager.getAppManager().getActivity(
					ChatMainActivity.class);
			if (chatMainActivity != null) {
				finish(true);
			} else {
				if (!TextUtils
						.isEmpty(mBeanDoctorMyDetail.DoctorRelationStatus)
						&& mBeanDoctorMyDetail.DoctorRelationStatus.equals("2")) {

					BeanChatTo beanChatTo = new BeanChatTo();
					beanChatTo.UserID = mBeanDoctorMyDetail.DoctorID;
					beanChatTo.NickName = mBeanDoctorMyDetail.DoctorName;
					beanChatTo.Gender = mBeanDoctorMyDetail.Gender;
					beanChatTo.Avatar = mBeanDoctorMyDetail.Avatar;

					ChatSession chatSession = ChatManager.getInstance()
							.getOrCreateChatSession(
									Long.valueOf(LoginUtil.getUserId()),
									beanChatTo);

					ChatUtil.jumpChat(this, chatSession,
							ChatConst.TYPE_ONLINE_CHAT_DOCTOR_MY);
				} else {
					showIfSendMessageDialog();
				}
			}

			break;
		case R.id.moreTextView:

			if (!TextUtils.isEmpty(mBeanDoctorMyDetail.DoctorRelationStatus)
					&& mBeanDoctorMyDetail.DoctorRelationStatus.equals("4")) {
				// delete
				showDelRelationDialogDelete();
			} else {
				showDelRelationDialog();
			}

			break;

		default:
			break;
		}
	}

	/**
	 * 是否发送聊天
	 */
	private void showIfSendMessageDialog() {
		String message = String.format("您与%s医生还不是医患关系，暂时无法联系，请耐心等待。",
				mBeanDoctorMyDetail.DoctorName);
		MyDialog dialog = new MyDialog(this)
				.setMessage(message)
				.setNegativeButtonSplitImageHide(true)
				.setPositiveButton(R.string.app_ok2,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}

	/**
	 * 是否解除医患关系
	 */
	private void showDelRelationDialog() {
		String message = String.format("确定解除和%s的医患关系吗？解除后将无法联系",
				mBeanDoctorMyDetail.DoctorName);
		MyDialog dialog = new MyDialog(this)
				.setTitle("解除关系")
				.setMessage(message)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.app_ok, new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// 删除医生
						releaseDoctor();
					}
				});

		dialog.create(null);
		dialog.showMyDialog();
	}

	/**
	 * 是否删除医生
	 */
	private void showDelRelationDialogDelete() {
		String message = String.format("您与%s医生还不是医患关系，医生必须添加你为患者才能开始聊天。",
				mBeanDoctorMyDetail.DoctorName);
		MyDialog dialog = new MyDialog(this)
				.setTitle("解除关系")
				.setMessage(message)
				.setNegativeButton(R.string.app_cancel,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {

							}
						})
				.setPositiveButton(R.string.chat_del_doctor,
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								
								// net request
								// ios没有调这个接口
								releaseDoctor();
								
//								Intent intent = new Intent(DoctorMyDetailActivity.this,DoctorMainActivity.class);
//								startActivity(intent, true);
							}
						});

		dialog.create(null);
		dialog.showMyDialog();
	}

	private void releaseDoctor() {
		showProgressDialog();
		DoctorManager.getInstance().requestDoctorDetailRelease(
				mBeanDoctorMyDetail.DoctorID, new AsyncRequest() {
					@Override
					public void RequestComplete(Object o, Object o1) {
						mHandler.sendEmptyMessage(MSG_RELEASE_DOCTOR_SUCCESS);
					}

					@Override
					public void RequestError(Object o, int i, String s) {
						mHandler.sendEmptyMessage(MSG_RELEASE_DOCTOR_FAIL);
					}
				});
	}

	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_RELEASE_DOCTOR_SUCCESS:
				hideProgressDialog();

				// finish(true);

				// DoctorMyActivity instance = (DoctorMyActivity) AppManager
				// .getAppManager().getActivity(DoctorMyActivity.class);
				// if (instance != null) {
				// instance.refreshData();
				// }
				
				// todo 主动解除
				DoctorManager
						.getInstance()
						.updateDoctorRelation(
								Long.valueOf(LoginUtil
										.getUserId()),
								mBeanDoctorMyDetail.DoctorID,
								Integer.valueOf(Constants.Relation.RELATION_CODE_RELEASE_TEXT));

				ChatManager.getInstance().resetChatMessages(mBeanDoctorMyDetail.DoctorID);

				Intent intent = new Intent(DoctorMyDetailActivity.this,
						IndexConsultActivity.class);
				startActivity(intent, true);

				break;
			case MSG_RELEASE_DOCTOR_FAIL:
				hideProgressDialog();
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			hideProgressDialog();

			mBeanDoctorMyDetail = BeanDoctorMyDetail
					.parseDetailInfo((String) data);
			if (mBeanDoctorMyDetail != null
					&& !TextUtils.isEmpty(mBeanDoctorMyDetail.DoctorName)) {
				initData();
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String data) {
		if (object.equals(REQUEST_DATA)) {
			hideProgressDialog();
		}
	}
}
